<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="" prop="platform">
        <!-- <el-input v-model="queryParams.platform" placeholder="请输入平台名称" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select
          v-model="queryParams.platform"
          placeholder="平台名称"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_sample_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="xhsNickname" label-width="100px">
        <el-input
          v-model="queryParams.xhsNickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="达人信息表ID" prop="sampleTalentInfoId">
        <el-input v-model="queryParams.sampleTalentInfoId" placeholder="请输入达人信息表ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="" prop="recipient">
        <el-input
          v-model="queryParams.recipient"
          placeholder="请输入收件人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入收件人地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
        <el-input v-model="queryParams.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleContact"
          >选择达人</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:contact:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:contact:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:contact:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:contact:export']"
          >导出</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button size="mini" plain icon="el-icon-plus" @click="chatlive"
          >批量寄样</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="contactList"
      @selection-change="handleSelectionChange"
      :height="600"
      @row-dblclick="trackingNumberHandle"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="联系ID" align="center" prop="id" />-->
      <el-table-column label="平台名称" align="center" prop="platform" />
      <el-table-column label="平台ID" align="center" prop="platformId" />
      <el-table-column label="昵称" align="center" prop="xhsNickname" />
      <el-table-column label="收件人" align="center" prop="recipient" />
      <el-table-column label="电话" align="center" prop="phone" />

      <el-table-column label="收货省份" align="center" prop="receiverState" />
      <el-table-column label="收货市" align="center" prop="receiverCity" />
      <el-table-column label="收货区" align="center" prop="receiverDistrict" />

      <el-table-column label="收件人地址" align="center" prop="address" />
      <!-- :formatter="formatData"  -->
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:contact:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:contact:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改联系方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        :inline="true"
      >
        <!-- <el-form-item label="达人信息表ID" prop="sampleTalentInfoId">
          <el-input v-model="form.sampleTalentInfoId" placeholder="请输入达人信息表ID" />
        </el-form-item> -->
        <el-form-item label="收件人" prop="recipient">
          <el-input v-model="form.recipient" placeholder="请输入收件人" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>

        <el-form-item label="所在区域" prop="">
          <el-row>
            <!-- <el-select v-model="form.receiverState" placeholder="请选择" @change="selectProvimce" style="width:130px">
              <el-option v-for="(item, index) of provincearr" :key="index" :label="item.name"
                :value="item.name"></el-option>
            </el-select>
            <el-select v-model="form.receiverCity" placeholder="请选择" @change="selectcity" style="width:130px">
              <el-option v-for="(item, index) of cityarr" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
            <el-select placeholder="请选择" v-model="form.receiverDistrict" style="width:150px">
              <el-option v-for="(item, index) of regionarr" :key="index" :label="item.name"
                :value="item.name"></el-option>
            </el-select> -->
            <el-select
              v-model="form.receiverState"
              clearable
              placeholder="省"
              @change="seletekey($event, 'province')"
              style="width: 130px"
            >
              <el-option
                v-for="(val, key) in provinces"
                :key="key"
                :label="val"
                :value="val"
              />
            </el-select>
            <el-select
              v-model="form.receiverCity"
              clearable
              placeholder="市"
              @change="seletekey($event, 'city')"
              style="width: 130px"
            >
              <el-option
                v-for="(val, key) in citys"
                :key="key"
                :label="val"
                :value="val"
              />
            </el-select>
            <el-select
              v-model="form.receiverDistrict"
              clearable
              placeholder="县区"
              @change="seletekey($event, 'area')"
              style="width: 150px"
              filterable
              allow-create
            >
              <el-option
                v-for="(val, key) in areas"
                :key="key"
                :label="val"
                :value="val"
              />
            </el-select>
          </el-row>
        </el-form-item>
        <el-form-item label="收件人地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入收件人地址"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注" />
        </el-form-item>
        <el-form-item label="文本粘贴" prop="">
          <el-input
            v-model="demo"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10 }"
            placeholder="省市区地址、姓名、电话11位用空格分开!!"
            style="width: 350px"
          ></el-input>
          <el-button type="primary" size="mini" @click="addText"
            >识别</el-button
          >
          <!-- <el-input v-model="sampleTalentPay.platform" placeholder="请输入平台名称" /> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="VisibleLive"
      append-to-body
      title="直播合作"
      width="800px"
      v-if="VisibleLive"
    >
      <el-form
        ref="fLive"
        :model="fLive"
        :rules="rules"
        label-width="110px"
        :inline="true"
      >
        <el-form-item label="是否归还" prop="isReturn">
          <!-- <el-input v-model="formVFU.isReturn" placeholder="是否归还" /> -->
          <el-select
            v-model="fLive.isReturn"
            placeholder="请选择是否归还"
            clearable
            filterable
          >
            <el-option
              v-for="dict in dict.type.sys_one_zero"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <!-- <el-input v-model="formVFU.expressCompany" placeholder="快递公司" /> -->
          <el-select
            v-model="fLive.expressCompany"
            placeholder="请选择快递公司"
            clearable
            filterable
          >
            <el-option
              v-for="dict in dict.type.sys_jst_sample_sf"
              :key="dict.label"
              :label="dict.label"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择款式" prop="">
          <el-select
            v-model="fLive.productNo"
            clearable
            filterable
            remote
            :remote-method="getDatas"
            :loading="loading"
            placeholder="货号编码"
            @change="testAdd(fLive.productNo)"
            style="width: 150px"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select
            ref="selectRef"
            v-model="fLive.colorProperty"
            clearable
            filterable
            placeholder="选择颜色"
            @change="testColor(fLive.productNo, fLive.colorProperty)"
            style="width: 200px"
          >
            <el-option
              v-for="item in ColorLike"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select
            ref="multiSelect"
            v-model="fLive.size"
            clearable
            placeholder="尺寸"
            style="width: 100px"
          >
            <el-option
              v-for="item in sizeList"
              :key="item.id"
              :label="item.size"
              :value="item.size"
            >
            </el-option>
          </el-select>
          <el-input
            ref="autoFocus"
            v-model="fLive.applyNum"
            placeholder="购买数量"
            style="width: 110px"
            type="number"
            oninput="value=value.replace(/^0|[^0-9]/g,'')"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item prop="productNum" label="购买数量">
          
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 50px">
        <el-button type="primary" @click="submitLive('fLive')">确 定</el-button>
        <!-- <el-button @click="canNew">取 消</el-button> -->
        <!-- <el-button @click="addDomain">新增</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSampleApply,
  getSampleApply,
  delSampleApply,
  addSampleApply,
  updateSampleApply,
  addApply,
  returnApply,
} from "@/api/sample/sampleApply";
import AddressParse from "address-parse";
//数据获取
import { pcaa } from "area-data";

import axios from "axios";
// import { province } from '@/api/sample/map'
import {
  listContact,
  getContact,
  delContact,
  addContact,
  updateContact,
} from "@/api/sample/contact";
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  addTemplateAndSecondry,
  addProNoColorSize,
  productNoLike,
} from "@/api/product/template";
import {
  listSecondry,
  getSecondry,
  delSecondry,
  addSecondry,
  updateSecondry,
  getInfoByName,
  productNoColorLike,
  listAll,
  colorLike,
  selectPicByProductNoColor,
} from "@/api/product/secondry";
export default {
  name: "Contact",
  dicts: [
    "sys_product_qudao",
    "sys_sample_status",
    "sys_sample_sf",
    "sys_one_zero",
    "sys_sample_day",
    "sys_sample_time",
    "sys_sample_name",
    "sys_sample_cj",
    "sys_jst_sample_sf",
  ],
  data() {
    return {
      list: [],
      //模糊匹配
      sizeList: [],
      ColorLike: [],
      options: [], // 选项，从后端传递过来
      VisibleLive: false,
      fLive: {
        isReturn: "是",

        expressCompany: "中通快递",
        applyNum: 1,
      },
      demo: "",
      //省市区
      pcaaData: pcaa,
      // 区域数据
      provinces: pcaa["86"],
      citys: [],
      areas: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 联系方式表格数据
      contactList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sampleTalentInfoId: null,
        phone: null,
        recipient: null,
        address: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sampleTalentInfoId: [
          { required: true, message: "达人信息表ID不能为空", trigger: "blur" },
        ],
        phone: [{ required: true, message: "电话不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    // this.provincearr = province
    this.getList();
  },
  methods: {
    handleContact() {
      if (this.list.length != 1) {
        this.$modal.msgError("请只选择一个达人");
        return;
      }
      this.$emit("trackingNumberHandle", this.list[0]);
    },
    trackingNumberHandle(row) {
      this.$emit("trackingNumberHandle", row);
    },
    /* 获取尺寸列表 */
    testColor(productNo, colorProperty) {
      listAll({ productNo: productNo, colorProperty: colorProperty }).then(
        (res) => {
          // this.loading = false;
          this.sizeList = res;
          console.log(JSON.stringify(res));
        }
      );
    },
    /* 获取颜色列表 */
    testAdd(key, index) {
      this.productNo = key;
      console.log();
      if (!key) {
        return;
      }
      productNoColorLike({ productNo: key }).then((res) => {
        // this.loading = false;
        this.ColorLike = res.data;
        console.log(JSON.stringify(this.ColorLike));
      });
    },

    /* 获取货号列表 */
    getDatas(key) {
      console.log(JSON.stringify(key));
      this.loading = true;
      // return
      productNoLike(key).then((res) => {
        this.loading = false;
        this.options = res.data;
        console.log(JSON.stringify(this.options));
      });
    },
    chatlive() {
      if (this.ids.length == 0) {
        this.$modal.msgError("请选择一个收件地址！");
        return;
      }
      this.VisibleLive = true;
    },

    //抽奖活动
    submitLive() {
      if (this.ids.length == 0) {
        this.$modal.msgError("请选择一个收件地址！");
        return;
      }
      var live = [];
      console.log(JSON.stringify(this.ids));
      this.ids.forEach((item) => {
        live.push({
          contactId: item,
          sampleTalentCooperateId: null,
          sampleTalentCooperateType: "live",
          sampleTalentInfoId: this.$route.query.id,
          ...this.fLive,
        });
      });
      addApply(live).then((response) => {
        this.VisibleLive = false;
        if (response.code == 200) {
          this.$modal.msgSuccess("新增成功");
          this.$router.push({
            path: "/sample/sampleApply",
            // query: { id: this.ids[0] },
          });
        }
      });
    },
    addText() {
      if (!this.demo) {
        this.$modal.msgError("请输入内容");
        return;
      }
      let address = this.demo.replace(/\s+/g, " ");
      const result = AddressParse.parse(address);
      this.form.phone = result[0].mobile ? result[0].mobile : "";
      this.form.recipient = result[0].name ? result[0].name : "";
      this.form.receiverState = result[0].province ? result[0].province : "";
      this.form.receiverCity = result[0].city ? result[0].city : "";
      this.form.receiverDistrict = result[0].area ? result[0].area : "";
      this.form.address = result[0].details;
      // axios({
      //   method: "post",
      //   url: "https://wangzc.wang/smAddress",
      //   // url: "http://47.97.123.182:1399/smAddress",
      //   data: {
      //     address: address,
      //   },
      // }).then((res) => {
      //   // console.log(JSON.stringify(res.data));
      //   this.form.phone = res.data.phone ? res.data.phone : "";
      //   this.form.recipient = res.data.name ? res.data.name : "";
      //   this.form.receiverState = res.data.province ? res.data.province : "";
      //   this.form.receiverCity = res.data.city ? res.data.city : "";
      //   this.form.receiverDistrict = res.data.county ? res.data.county : "";
      //   this.form.address = res.data.street
      //     ? res.data.street + res.data.address
      //     : res.data.address;
      //   // if (!this.form.receiverDistrict) {

      this.seletekey(this.form.receiverState, "province");
      this.seletekey(this.form.receiverCity, "city");
      this.seletekey(this.form.receiverDistrict, "area");

      let obj = {
        fullAddress: this.demo,
        province: this.form.receiverState,
        city: this.form.receiverCity,
        district: this.form.receiverDistrict,
        detailedAddress: this.form.address,

        recipientPhone: this.form.phone,
        recipientName: this.form.recipient,
      };

      axios({
        method: "post",
        url: "http://47.107.129.160:9001/prod-api/product/parsing",
        // url: "http://47.97.123.182:1399/smAddress",
        data: obj,
      }).then((response) => {});
    },
    seletekey(e, type) {
      if (e) {
        switch (type) {
          case "province":
            Object.keys(this.provinces).filter((item) => {
              if (this.provinces[item] === e) {
                this.citys = this.pcaaData[item];
              }
            });
            break;
          case "city":
            Object.keys(this.citys).filter((item) => {
              if (this.citys[item] === e) {
                this.areas = this.pcaaData[item];
              }
            });
            break;
          case "area":
            this.form.receiverDistrict = e;
            this.$forceUpdate();
            break;
        }
      }
    },
    //点击某一行
    t(row, column, cell, event) {
      console.log(row, column, cell, event);
      this.handleUpdate(row);
    },
    formatData(row) {
      console.log(JSON.stringify(row));
      // let rowPerson = (row) || [];
      // let arr = [];
      // rowPerson.forEach(item => {
      //   //如果数据特别多的话,还可以在这里加if判断,仅展示规定的数据
      //   arr.push(item.size);
      // });
      //
      return (
        row.receiverState +
        row.receiverCity +
        row.receiverDistrict +
        row.address
      );
    },
    /** 查询联系方式列表 */
    getList() {
      let queryParam = null;

      queryParam = this.$route.query.id;

      // console.log();

      this.loading = true;
      listContact(this.queryParams).then((response) => {
        this.contactList = response.rows;
        console.log(JSON.stringify(this.contactList));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sampleTalentInfoId: null,
        phone: null,
        recipient: null,
        address: null,
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.list = selection.map((item) => item);
      console.log(JSON.stringify(this.list));
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.$route.query.id) {
        this.$modal.msgError("禁止添加,请从达人信息菜单-联系配置进入");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加联系方式";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getContact(id).then((response) => {
        this.form = response.data;
        this.seletekey(this.form.receiverState, "province");
        this.seletekey(this.form.receiverCity, "city");
        this.seletekey(this.form.receiverDistrict, "area");
        this.open = true;
        this.title = "修改联系方式";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.form.recipient) {
        this.$modal.msgError("请输入收件人");
        return;
      }
      if (!this.form.receiverState) {
        this.$modal.msgError("请选择收货省份");
        return;
      }
      if (!this.form.receiverCity) {
        this.$modal.msgError("请选择收货城市");
        return;
      }
      if (!this.form.receiverDistrict) {
        this.$modal.msgError("请选择收货管辖区");
        return;
      }
      if (!this.form.address) {
        this.$modal.msgError("请输入收件人地址");
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateContact(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.sampleTalentInfoId = this.$route.query.id;
            addContact(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否删除该地址？")
        .then(function () {
          return delContact(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/contact/exportAllTalent",
        {
          ...this.queryParams,
        },
        `contact_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
